import sys
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QHeaderView, QAbstractItemView, QTableWidgetItem
from src.form import Ui_MainWindow
from add_stu import Ui_Form
from find_stu import Ui_Form as Ui_FindForm

from dao.base import Mydb, func


class MyMainWindow(QMainWindow):

    def __init__(self, widget=None):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # 设置自适应和禁止表格修改内容
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # 点击按钮打开子窗口
        self.ui.pushButton_add.clicked.connect(self.open_windows)
        self.ui.pushButton_find.clicked.connect(self.open_find_windows)
        self.ui.pushButton_update.clicked.connect(self.open_windows)
        self.ui.pushButton_del.clicked.connect(self.open_del_windows)

        # 清除原有的数据
        self.ui.tableWidget.clear()
        # 初始化加载数据库的数据
        self.mydb = Mydb()
        self.mydb.completed.connect(self.receive_form_mysql)  # 连接信号槽
        # 查询数据，触发信号加载数据
        self.mydb.query()

    def receive_form_mysql(self, data: list):

        for i in data:
            temp = list(map(str, i))
            self.add_data2(temp)
        return

        # 第二步： 槽函数

    def addDataToTable(self, name, age, score):
        data = [name, age, score]
        self.add_data2(data)

    def add_data2(self, data):
        row = self.ui.tableWidget.rowCount()
        self.ui.tableWidget.insertRow(row)  # 在表格中插入新行

        for j, value in enumerate(data):
            item = QTableWidgetItem(value)
            self.ui.tableWidget.setItem(row, j, item)

        return

        items = data
        # 获取表格的行数
        row = self.ui.tableWidget.rowCount()
        # 获取tableWidget中已有的姓名name列表
        existing_names = [self.ui.tableWidget.item(i, 0).text() for i in range(row)]

        # 判断data中的第一个数据是否已经存在于tableWidget中
        name = data[0]
        if name != "" and name not in existing_names:
            # 如果姓名不为空且不存在，添加新行
            self.ui.tableWidget.insertRow(row)
            # 向新行中插入数据
            for j in range(len(data)):
                item = QTableWidgetItem(str(data[j]))
                self.ui.tableWidget.setItem(row, j, item)
        elif name != "":
            # 如果姓名不为空且存在，更新该行的数据
            index = existing_names.index(name)
            for j in range(len(data)):
                item = QTableWidgetItem(str(data[j]))
                self.ui.tableWidget.setItem(index, j, item)

    def findDataToTable(self, name):
        self.tableWidget = self.ui.tableWidget
        self.rowCount = self.ui.tableWidget.rowCount()

        # 遍历行并搜索姓名
        for row in range(self.rowCount):
            item = self.tableWidget.item(row, 0)
            if item and item.text() == name:
                # 高亮整行
                for col in range(self.tableWidget.columnCount()):
                    item = self.tableWidget.item(row, col)
                    if item:
                        item.setBackground(Qt.green)

    def delDataToTable(self, name):
        self.tableWidget = self.ui.tableWidget
        self.rowCount = self.ui.tableWidget.rowCount()

        # 遍历行并搜索姓名
        for row in range(self.rowCount):
            item = self.tableWidget.item(row, 0)
            if item and item.text() == name:
                # 清空找到的整行信息
                for col in range(self.tableWidget.columnCount()):
                    item = self.tableWidget.item(row, col)
                    if item:
                        item.setText("")  # 清空该单元格的文本内容
                break

    def open_windows(self):
        self.child = ChildWindow()
        self.child.completed.connect(self.addDataToTable)  # 第三步：连接 child_Window 的 completed 信号和槽函数
        self.child.show()

    def open_find_windows(self):
        self.child2 = FindWindow()
        self.child2.completed_find.connect(self.findDataToTable)
        self.child2.show()

    def open_del_windows(self):
        self.child2 = FindWindow()
        self.child2.completed_del.connect(self.delDataToTable)
        self.child2.show()


class ChildWindow(QWidget):
    completed = pyqtSignal(str, str, str)  # 第一步：定义信号

    def __init__(self):
        super().__init__()
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.pushButton_go.clicked.connect(self.add_data)

    def add_data(self):
        name = self.ui.lineEdit_name.text()
        age = self.ui.lineEdit_age.text()
        score = self.ui.lineEdit_score.text()

        self.completed.emit(name, age, score)  # 第四步：发送信号


class FindWindow(QWidget):
    completed_find = pyqtSignal(str)
    completed_del = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.ui = Ui_FindForm()
        self.ui.setupUi(self)
        self.ui.pushButton_go_find.clicked.connect(self.find_data)
        self.ui.pushButton_go_del.clicked.connect(self.del_data)

    def find_data(self):
        name = self.ui.lineEdit_name_2.text()
        self.completed_find.emit(name)

    def del_data(self):
        name = self.ui.lineEdit_name_2.text()
        self.completed_del.emit(name)


def main():
    app = QApplication(sys.argv)
    window = MyMainWindow()
    window.show()  # 显示主窗口

    sys.exit(app.exec_())  # 确保应用正常退出


if __name__ == '__main__':
    main()
